package ssm.integration.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * description: 持久层配置类-05
 * TODO：MyBatis组件 SqlSessionFactoryBean、MapperScannerConfigurer
 *      方式2：MyBatis完全配置类，无需外部配置文件 mybatis-config.xml，推荐
 *
 * 1. 保留数据库连接池的配置类 DataSourceJavaConfig
 * 2. 保留MyBatis组件 SqlSessionFactoryBean 创建 SqlSessionFactoryBean
 * 3. 保留MyBatis组件 MapperScannerConfigurer 创建 Mapper 代理对象
 * 4. 通过 SqlSessionFactoryBean 的方法指定MyBatis配置，替换 mybatis-config.xml文件功能
 */

@Configuration
public class MapperJavaConfigNew {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        //指定配置文件等信息

        //指定数据库连接池对象
        sqlSessionFactoryBean.setDataSource(dataSource);

        // TODO：指定mybatis配置，替换mybatis-config.xml文件功能

        // TODO: Configuration替换配置文件的<settings>部分
        org.apache.ibatis.session.Configuration configuration
                = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setLogImpl(Slf4jImpl.class);
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        // TODO：指定<settings>配置，驼峰式映射、日志输出、结果映射
        sqlSessionFactoryBean.setConfiguration(configuration);

        // TODO：别名设置
        sqlSessionFactoryBean.setTypeAliasesPackage("ssm.integration.pojo");

        // TODO: pagehelper插件设置
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect","mysql");
        pageInterceptor.setProperties(properties);
        // TODO: 指定pagehelper插件
        sqlSessionFactoryBean.addPlugins(pageInterceptor);

        return sqlSessionFactoryBean;
    }

    //mapper代理对象加入到ioc
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        // 通过扫描指定路径下的Mapper接口，生成代理对象。
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //mapper接口和mapper.xml所在的共同包
        mapperScannerConfigurer.setBasePackage("ssm.integration.mapper");
        return mapperScannerConfigurer;
    }
}
